import { hasCustomKey } from '@/api'
import { navTo } from '@/router'
import { useAppStore } from '@/store/app'
import { showToast } from '@/utils/uni'
import { AjaxResponse } from 'uni-ajax'
import { pageCtx } from '@/utils'
import { authApi } from '@/api/server'

export const ERROR_OVERWRITE: Record<string, string> = {
  // 重写错误代码对应的toast消息内容
  '003000': '不合法的Token',
}

export const toastError = (err: Error | AjaxResponse) => {
  console.log('toast err', err)
  if ((err as { errMsg: string })?.errMsg === 'request:fail abort') {
    // request abort
    return Promise.reject(err)
  }
  const isError = err instanceof Error
  if (isError || !hasCustomKey(err.config, 'noToast')) {
    const title = isError ? err.message : ERROR_OVERWRITE[err.data?.code] ?? (err.data?.msg || '系统错误')
    setTimeout(() => showToast(title), 100)
  }
  return Promise.reject(err)
}

export const navLogin = async (err: Error | AjaxResponse | any) => {
  console.log(err, 'err.data')
  // TODO 未登录判断
  const errPromise = Promise.reject(err)
  if (err?.statusCode === 403) {
    // showToast('认证信息已过期，已为你重新认证！')
    const { code } = await uni.login()
    const res = await authApi(code)
    const { token: newToken, userId } = res
    const appStore = useAppStore()
    appStore.updateToken(newToken)
    appStore.updateUserId(userId)
    const { route } = pageCtx() ?? {}
    return navTo('/' + route, 'launch')
  } else {
    if (err instanceof Error) return errPromise
    return errPromise
  }
}
